package front

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/gorilla/websocket"
)

type connection struct {
	ws   *websocket.Conn
	Sc   chan Message // 用户消息池
	Data *ClientData  // 用户信息
}

func (c *connection) writer() {
	// 持续消费个人消息池消息
	for msg := range c.Sc {
		_ = c.ws.WriteMessage(websocket.TextMessage, func() (res []byte) {
			res, _ = json.Marshal(msg)
			return
		}())
	}
	_ = c.ws.Close()
}

// render 处理用户消息
func (c *connection) reader() {
	for {
		var msg Message
		_, message, err := c.ws.ReadMessage()
		if err != nil {
			HUB.R <- c
			break
		}
		_ = json.Unmarshal(message, &msg)
		msg.FromID = c.Data.UserId
		msg.SourceType = "client"
		msg.Time = time.Now().Format("2006-01-02 15:04:05")

		switch msg.Type {
		case "public":
			go func() {
				HUB.OnlineMsgPool <- msg
			}()
		case "group":
			if msg.GroupID != "" {
				// 遍历组列表
				// 获取组内成员
				// 发送消息
			}
		case "private":
			if msg.PrivateToID != "" {
				go func() {
					HUB.OnlineMsgPool <- msg
				}()
			}
		case "report":
		case "connect":
		default:
			fmt.Printf("default: %s\n", msg.Data)
		}
	}
}
